﻿
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

using System.Data;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data.SqlClient;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http;


using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System.Web;
using Models.Common;
using UtilsORM.MySqlData;
using UtilsORM;
using ServiceWeb.WebAdmin;
using ServiceWeb.DBGateway;
using UtilsBase;
using UtilsCache;

namespace GatewayServer.Controllers
{
    public class MagerLoginController : Controller
    {
        // GET: MagerLogin

        public IActionResult Index()
        {

            return View();
        }
        public IActionResult Login()
        {


            return View();
        }



        [HttpPost]
        public string LoginCheck(string Emp_Mobile, string Emp_Pwd)
        {

            string returnvalue = "";
            try
            {
                Emp_Pwd = UtilsDecrypt.DoMd5Encode(Emp_Pwd.Trim(), "32");
                returnvalue = toLogin(Emp_Mobile.Trim(), Emp_Pwd);
                if (returnvalue == "1")
                {
                    return "[{\"respCode\":\"" + ResponseCode.USER_INFO_ERROR + "\",\"respMsg\":\"用户没有权限\",\"url\":\"\"}]";
                }
                else if (returnvalue == "2")
                {
                    string url = "/magermain/index";
                    if (!string.IsNullOrEmpty(Request.Query["from"]))
                    {
                        url = Request.Query["from"];
                    }
                    return "[{\"respCode\":\"" + ResponseCode.SUCCESS + "\",\"respMsg\":\"" + ResponseCode.SUCCESS_MSG + "\",\"url\":\"" + url + "\"}]";
                }
                else if (returnvalue == "3")
                {
                    return "[{\"respCode\":\"" + ResponseCode.USER_INFO_ERROR + "\",\"respMsg\":\"用户名和密码验证不通过。\",\"url\":\"\"}]";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return "[{\"respCode\":\"" + ResponseCode.System_ERROR + "\",\"respMsg\":\"" + ResponseCode.System_ERROR_MSG + " " + ex.Message + "\",\"url\":\"\"}]";

            }
            return returnvalue;
        }
        protected string toLogin(string Emp_Mobile, string Emp_Pwd)
        {
            //UtilsBase.//Log4netFactory.WriteInfo("ssoLoginInfo " + Emp_Mobile, Startup.repository.Name, "ssoLoginInfo");
            //登录验证

            bs_client_user model = new ServiceCompanyUser().LoginCheck(Emp_Mobile, Emp_Pwd);
            if (model != null)
            {
                //写cookie
                bool wbool = writeCookie(model.cu_guid);
                if (wbool == false)
                {
                    return "1";
                }
                return "2";
            }
            else
            {
                return "3";

            }
        }

        //页面跳转
        public void ssoLoginPage()
        {
            Response.Redirect("/magermain/index");
        }


        /// <summary>
        /// 写cookie
        /// </summary>
        /// <param name="Emp_Guid"></param>
        public bool writeCookie(string Emp_Guid)
        {
            try
            {
                MagerLoginInfo magerLoginInfo = new MagerLoginInfo();
                string sql = @"select * from bs_client_user where cu_guid=@emp_guid  ";
                DataTable dt = new MySqlYihongIot().Db.Ado.GetDataTable(sql, new { emp_guid = Emp_Guid });// DBUtility.MySqlHelper.GetDataTable(sql, sqlp);
                if (dt.Rows.Count > 0)
                {

                    magerLoginInfo.user_guid = Emp_Guid;
                    magerLoginInfo.user_Name = dt.Rows[0]["cu_name"].ToString();
                    magerLoginInfo.userCompanyGuid = dt.Rows[0]["cu_c_guid"].ToString();

                    if (dt.Rows[0]["cu_power_type"].ToString() == "super")
                    {
                        magerLoginInfo.isSupperAdmin = true;
                    }


                }
                dt.Dispose();




                if (magerLoginInfo.isSupperAdmin == false)
                {//查角色
                    string rolecode = "";

                    sql = "select * from bs_manage_user_role inner join bs_manage_role on r_guid=ur_r_guid where ur_cu_guid=@empguid";
                    dt = new MySqlYihongIot().Db.Ado.GetDataTable(sql, new { empguid = Emp_Guid });
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {//读取角色
                        if (dt.Rows[i]["r_guid"].ToString() != Guid.Empty.ToString())
                        {
                            rolecode = dt.Rows[i]["r_code"].ToString();
                        }
                    }
                    dt.Dispose();
                    if (rolecode == "")
                    {
                        //Log4netFactory.WriteError(("登录没有权限", "--", "--");
                        //没有权限
                        return false;

                    }
                }


                new DBManageSystemLog().WriteLog(magerLoginInfo, "后台登录");



                string GetTimeStamp = UtilsDateTime.getTimeStamp().ToString();
                HttpContext.SetCookies("Data_LoginInfo", HttpUtility.UrlEncode(UtilsDecrypt.MD5Encrypt(UtilAppsettingCache.getSetting("MyWebSite:CookiesKey") + Emp_Guid + GetTimeStamp) + "|" + Emp_Guid + "|" + GetTimeStamp));
                //删除缓存
                UtilMemoryCacheHelper.remove("bs_logintoken_" + Emp_Guid.ToString().ToUpper());

            }
            catch (Exception ex)
            {
                //Log4netFactory.WriteError((ex, "--", "--");
                return false;
            }

            return true;
        }


        public IActionResult LogOut()
        {
            ///退出登录


            HttpContext.DeleteCookies("Data_LoginInfo");

            //url = "?from=" + Request.Query["from"];
            string url = UtilAppsettingCache.getSetting("MyWebSite:LoginUrl");
            return Redirect(url);// ("Login", "MagerLogin");
            //return View("Login", "MagerLogin"); 
        }


        public IActionResult NoPower()
        {
            return View();
        }
    }
}
